package com.gitee.feizns.web.mvc.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * @author feizns
 * @since 2019/7/25
 */
public class StringToEnumsIgnoreCaseConverterFactory implements ConverterFactory<String, Enum<?>> {

    @Override
    public <T extends Enum<?>> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends Enum> implements Converter<String, T> {

        private Class<T> targetType;

        public StringToEnum(Class<T> targetType) {
            this.targetType = targetType;
        }

        @Override
        public T convert(String source) {
            T[] constants = targetType.getEnumConstants();
            for (T constant : constants) {
                if ( constant.name().equalsIgnoreCase(source) )
                    return constant;
            }
            return null;
        }

    }

}
